package com.fzebu.fastboot.util;

import com.alibaba.fastjson.JSON;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author: Jack
 * @create: 2019/12/2 19:03
 * @version: 1.0.0
 **/
public class ParamsUtil {

    public static <T> T toJavaBean(HttpServletRequest request, Class<T> clazz) {
        String str = readRequest(request);
        return JSON.parseObject(str, clazz);
    }

    public static <T> List<T> toJavaArray(HttpServletRequest request, Class<T> clazz) {
        String str = readRequest(request);
        return JSON.parseArray(str, clazz);
    }

    private static String readRequest(HttpServletRequest request) {
        try {
            BufferedReader streamReader = new BufferedReader(
                    new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                sb.append(inputStr);
            }
            return sb.toString();
        } catch (IOException e) {
            return null;
        }
    }

}
